const Model = require('./Model')
const hash = require('../tools/passHash')

class User extends Model {
    // 登录
    static doLogin(phone) {
        return new Promise((resolve, reject) => {
            const sql = 'SELECT id, username, password, r_id FROM `user` WHERE phone=?';
            this.query(sql, [phone])
                .then(resolve)
                .catch(reject);
        });
    };
    // 根据id查找用户 参数id：用户的id
    static selUser(id) {
        return new Promise((resolve, reject) => {
            const sql = 'SELECT id, username, email, userTime, avator, phone FROM `user` WHERE id=?';
            this.query(sql, [id])
                .then(resolve)
                .catch(reject);
        });
    }

    // 注册
    static toRegister(username, password, email, phone) {

        return new Promise((resolve, reject) => {
            const sql = 'INSERT INTO `user` (username, password, email, userTime, r_id, salt, phone) VALUES(?, ?, ?, CURRENT_TIMESTAMP, 1, ?, ?)';
            hash.getPassword(password, 6, (cipher, salt) => {
                this.query(sql, [username, cipher, email, salt, phone])
                    .then(resolve)
                    .catch(resolve);
            });
        });

    }

    // 查询所有用户
    static getAllUser() {
        return new Promise((resolve, reject) => {
            const sql = 'SELECT id, username, email, userTime, phone FROM `user`';
            this.query(sql)
                .then(resolve)
                .catch(reject);
        });
    }

    // 重置密码
    static rePassword(password, salt, id) {
        return new Promise((resolve, reject) => {
            const sql = 'UPDATE `user` SET  password = ?, userTime=CURRENT_TIMESTAMP, salt = ? WHERE id = ?';
            this.query(sql, [password, salt, id])
                .then(resolve)
                .catch(reject);
        });
    }

    // 更新用户信息
    static reInformation(username, email, phone) {
        return new Promise((resolve, reject) => {
            const sql = 'UPDATE `user` SET username=?, email=?, userTime=CURRENT_TIMESTAMP WHERE phone=?';
            this.query(sql, [username, email, phone])
                .then(resolve)
                .catch(reject);
        });
    }

    // 删除用户
    static delUser(id) {
        return new Promise((resolve, reject) => {
            const sql = 'DELETE FROM `user` WHERE id = ?'
            this.query(sql, [id])
                .then(resolve)
                .catch(reject);
        });
    }


    // 最后登录时间
    static lastLoginTime() {
        return new Promise((resolve, reject) => {
            const sql = "SELECT `time` FROM log WHERE handle='登录' ORDER BY `time` DESC LIMIT 1";
            this.query(sql)
                .then(resolve)
                .catch(reject);
        });
    }
}

module.exports = User;
